# Build recipe for mercurial.
#
# Copyright (C) 2022-2023 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Exit immediately on any error
set -e

program=mercurial
version=6.4.2
release=1

# Define a category for the output of the package name
pkgcategory=devel

tarname=${program}-${version}.tar.gz

# Remote source(s)
fetch=https://www.mercurial-scm.org/release/$tarname

description="
A fast scalable distributed SCM system.

Mercurial is a distributed SCM tool written in Python.  It is used by
a number of large projects that require fast, reliable distributed
revision control, such as Mozilla.
"

homepage=https://www.mercurial-scm.org
license=GPLv2+

docs="CONTRIBUTING CONTRIBUTORS COPYING PKG-INFO README* relnotes/6.3"
docsdir="${docdir}/${program}-${version}"

build()
{
    unpack "${tardir}/$tarname"

    cd "$srcdir"

    # Set sane permissions
    chmod -R u+w,go-w,a+rX-s .

    python3 setup.py build
    python3 setup.py install --prefix=/usr --root="$destdir" --optimize=1

    # Install Mercurial server from contrib directory

    make -j${jobs} -C contrib/chg PREFIX=/usr DESTDIR="$destdir" install
    strip --strip-unneeded "${destdir}/usr/bin/chg"

    # Install wrapper for SSH access, and an extension for Tk

    install -p -m 755 contrib/hg-ssh "${destdir}/usr/bin"
    install -p -m 755 contrib/hgk "${destdir}/usr/bin"

    # Install syntax files for Emacs, Vim

    for file in contrib/*.el
    do
        install -p -m 644 "$file" \
         -D "${destdir}/usr/share/emacs/site-lisp/$file"
    done
    unset -v file

    install -p -m 644 contrib/vim/HGAnnotate.vim \
     -D "${destdir}/usr/share/vim/vimfiles/syntax/HGAnnotate.vim"

    # Add custom instructions for SSL certificate to Mercurial config

    mkdir -p "${destdir}/etc/mercurial"
    cat << EOF > "${destdir}/etc/mercurial/hgrc"
[web]
cacerts = /etc/ssl/certs/ca-certificates.crt
EOF

    # To handle config file(s)
    touch "${destdir}/etc/mercurial/.graft-config"

    # Compress and link man pages (if needed)
    if test -d "${destdir}/$mandir"
    then
        (
            cd "${destdir}/$mandir"
            find . -type f -exec lzip -9 {} +
            find . -type l | while read -r file
            do
                ln -sf "$(readlink -- "$file").lz" "${file}.lz"
                rm -- "$file"
            done
        )
    fi

    # Copy documentation
    mkdir -p "${destdir}/$docsdir"
    cp -p $docs "${destdir}/$docsdir"
}

